
/**
 * 设置cookie
 * @param {*} key    键名
 * @param {*} value  键值
 * @param {*} expires  过期时间(单位:s)
 * @param {*} path    存储路径
 * @return {*}  undefined
 */

function setCookie(key, value, expires = null, path = "/") {
    if (expires === null || expires === undefined) { // 不设置过期时间 => 浏览器关闭就过期
        var date = new Date();
        date.setSeconds(date.getSeconds() + expires);
        document.cookie = key + "=" + value + "; path=" + path;
    } else {
        var date = new Date();
        date.setSeconds(date.getSeconds() + expires);
        document.cookie = key + "=" + value + "; expires=" + date.toUTCString() + "; path=" + path;
    }
}


/**
 * 
 * @param {*} key  键名
 * @returns 对应键名返回键值,没有就返回undefined
 */
function getCookie(key) {
    var cookie = document.cookie;
    if (cookie) { // 有数据在解析
        var list = cookie.split("; ");
        for (var i = 0; i < list.length; i++) {
            var item = list[i]; // 'user=a123123', 'pwd=123123'
            var name = item.split("=")[0];
            var val = item.split("=")[1];

            if (key === name) {
                return val;
            }
        }
    }
    return "";
}


/**
 * 对应键名 删除cookie
 * @param {*} key  键名
 */
function deleteCookie(key) {
    setCookie(key, "", -1);
}

/* function clearCookie() {
    var cookie = document.cookie;
    if (cookie) { // 有数据在解析
        var list = cookie.split("; ");
        for (var i = 0; i < list.length; i++) {
            var item = list[i]; // 'user=a123123', 'pwd=123123'
            var name = item.split("=")[0];
            deleteCookie(name);
        }
    }
    return "";
} */
